package com.kotlin.book.adapter

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.book.activity.DetailActivity
import com.kotlin.book.databinding.ItemClassRightBinding
import com.kotlin.book.entry.Book
import com.kotlin.book.util.Util

class ClassRightItemAdapter(private var itemList: List<Book>) :
    RecyclerView.Adapter<ClassRightItemAdapter.ViewHolder>() {
    class ViewHolder(itemBinding: ItemClassRightBinding) :
        RecyclerView.ViewHolder(itemBinding.root) {
        val bookImage = itemBinding.bookImage
        val authorName = itemBinding.authorName
        val otherText = itemBinding.otherText
        val bookTag = itemBinding.bookTag
        val bookName = itemBinding.bookName
        val bookScore = itemBinding.bookScore
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding =
            ItemClassRightBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return itemList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = itemList[position]
        holder.bookName.text = item.name
        holder.authorName.text = item.author ?: ""
        val word = item.word?.toInt().toString() + "万字"
        holder.otherText.text = " · ${word} | ${item.state ?: ""}"
        holder.bookTag.text = item.tag
        holder.bookScore.text = item.source.toString()
        Util.getImage(item.pic, holder.bookImage, holder.itemView.context)

        holder.itemView.setOnClickListener {
            // 页面跳转
            val intent = Intent(holder.itemView.context, DetailActivity::class.java)
            val bundle = Bundle()
            // 传参
            bundle.putInt("id", item.id)
            intent.putExtras(bundle)
            holder.itemView.context.startActivity(intent)
        }

    }

    fun setData(newBooks: List<Book>) {
        itemList = newBooks
        notifyDataSetChanged()
    }

}